<template>
    <div>
    <basic-container>
      <avue-crud
        :option="tableOption"
        :data="tableData"
        :table-loading="tableLoading"
        :page="page"
        ref="crud"        
        @refresh-change="handleRefreshChange"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
        @search-change="handleSearchChange"
      >

    <template slot="menu" scope="scope">
        <div>
          <el-button v-perm="'/admin/order/item/refund_apply/process:resolve:anchor'"
           @click="handleAggreeRefund(scope.row)" size="mini" type="primary" 
           v-if="scope.row.refundApplyProcessStatus==1 && orderType==2">
            同意退款
          </el-button>
          <el-button v-perm="'/admin/order/item/refund_apply/process:resolve'"
           @click="handleAggreeRefund(scope.row)" size="mini" type="primary" 
           v-if="scope.row.refundApplyProcessStatus==1 && orderType==1">
            同意退款
          </el-button>
          <el-button v-perm="'/admin/order/item/refund_apply/process:reject'" @click="handleRejectRefund(scope.row)" size="mini" type="warning" 
            v-if="scope.row.refundApplyProcessStatus==1 && orderType==1">
            拒绝退款
          </el-button>
          <el-button v-perm="'/admin/order/item/refund_apply/process:reject:anchor'" 
            @click="handleRejectRefund(scope.row)" size="mini" type="warning" 
            v-if="scope.row.refundApplyProcessStatus==1 && orderType==2">
            拒绝退款
          </el-button>
          <el-button v-perm="'/admin/order/item/refund_apply/confirm_receive'" 
            @click="handleRefundReceiveGoods(scope.row)" size="mini" type="warning" 
            v-if="scope.row.refundApplyProcessStatus==3 && orderType==1">
            确认收货
          </el-button>
          <el-button v-perm="'/admin/order/item/refund_apply/confirm_receive:anchor'" 
            @click="handleRefundReceiveGoods(scope.row)" size="mini" type="warning" 
              v-if="scope.row.refundApplyProcessStatus==3 && orderType==2">
            确认收货
          </el-button>
        </div>
      </template>
      
      <template slot="menuLeft">
        <el-button
        type="primary"
        @click="handleExport"
        :loading="downloadLoading"
        v-if="orderType == 2"
        icon="el-icon-download"
        v-perm="'/admin/order/item/list_refund:export:anchor'"
        size="small"
      >导出</el-button>
        <el-button
        type="primary"
        @click="handleExport"
        :loading="downloadLoading"
        v-if="orderType == 1"
        icon="el-icon-download"
        v-perm="'/admin/order/item/list_refund:export'"
        size="small"
      >导出</el-button>
      </template>
      </avue-crud>
      </basic-container>
      <el-dialog :visible.sync="sendOrderDialogShowed" title="发货" width="600px">
        <div style="padding:0 30px">
            <el-form :disabled="isSubmiting" :model="sendOrderFormData" :rules="sendOrderFormRules" label-position="left"
              label-width="120px" ref="form1">
            <el-form-item prop="expressCompanyCode" label="快递公司">
              <!-- <el-input v-model="sendOrderFormData.expressCompany" placeholder="请输入快递公司"></el-input> -->
              <el-select  filterable v-model="sendOrderFormData.expressCompanyCode">
                <el-option :label="item.companyName" v-for="(item,itemIndex) in expressCompanies" :key="itemIndex" :value="item.companyCode">
                  {{item.companyName}}
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="expressNo" label="快递单号">
              <el-input v-model="sendOrderFormData.expressNo" placeholder="请填写快递单号"></el-input>
            </el-form-item>
        </el-form>
        </div>
        
         <div slot="footer" class="dialog-footer">
              <el-button @click="sendOrderDialogShowed = false">取消</el-button>
              <el-button :loading="isSubmiting" type="primary" @click="submitFormAction">确定</el-button>
          </div>
      </el-dialog>
    </div>
    
  </template>
  <script>
  import { validatenull } from "@/util/validate";
  import { filterForm } from "@/util/util";
  // import { DIC } from "@/const/dic";
  import {  getLabelFromDicV2 } from "@/const/dic";
  import { nowDate } from "../../util/date";
  import * as apiObj from "../../api/orderInfo";
  import { refundOrderInfoTableOption} from "@/const/orderInfo/refundOrderInfoTableOption.js";
  
  export default {
    data() {
      return {
        sendOrderFormData:{
          expressNo:'',
          expressCompany:'',
          expressCompanyCode:'',
          orderNo:''
        },
        expressCompanies:[],
        sendOrderFormRules:{
            expressCompanyCode:[{
              required:true,
              message:'请选择快递公司'
            }],
            expressNo:[
            {
               required:true,
              message:'请填写快递单号'
            }]
        },
        isSubmiting:false,
        bachDeleting: false,
        tableOption: {}, //表格设置属性
        tableData: [], //表格的数据
        downloadLoading:false,
        sendOrderDialogShowed:false,
        tableLoading: false,
        tableQueryParam: {
          orderType:1
        },
        page: {
          total: 0, //总页数
          currentPage: 1, //当前页数
          pageSize: 10 //每页显示多少条
        }
      };
    },
    props:{
      orderType:{
        type:Number,
        default:1
      }
    },
    filters:{
      refundApplyProcessStatusFilter(v){
        if(v){
          return ['买家申请退款',
    '商家拒绝退款',
    '商家待确认收货',
    '待退款',
    '已退款'][v-1];
        }
        return '';
      },
      skuPropsFilter(v){
        try{
          v = JSON.parse(v);
          return Object.keys(v).map(key=>{
            return key + ': ' + v[key]
          }).join(';');
        }catch(e){
          console.error(e);
        }
        return '';
      }
    },
    created() {
      //初始化数据格式
      if(this.orderType != 2) {
        refundOrderInfoTableOption.column.filter(el=>el.prop == 'userMobile' || el.prop == 'realName').forEach(el=>el.hide = true);
      } else {
        refundOrderInfoTableOption.column.filter(el=>el.prop == 'userMobile' || el.prop == 'realName').forEach(el=>el.hide = false);
      }
      this.tableOption = refundOrderInfoTableOption;
      this.handleList();
      this.loadExpressCompanies();
    },
    methods: {      
      handleAggreeRefund(row){
           this.confirm("确定同意退款吗").then(() => {
            apiObj.aggreeRefund({ itemId: row.id,processStatus:1 }).then(() => {
              this.success();
              this.handleList();
            });
          });
      },
      handleRejectRefund(row){
           this.confirm("确定拒绝退款吗").then(() => {
            apiObj.aggreeRefund({ itemId: row.id,processStatus:0 }).then(() => {
              this.success();
              this.handleList();
            });
          });
      },
      handleRefundReceiveGoods(row){
           this.confirm("确定收货了吗").then(() => {
            apiObj.receiveRefundGoods({ itemId: row.id }).then(() => {
              this.success();
              this.handleList();
            });
          });
      },
      handleSureRefund(row){
           this.confirm("确认退款了吗").then(() => {
            apiObj.sureRefund({ itemId: row.id,processStatus:1 }).then(() => {
              this.success();
              this.handleList();
            });
          });
      },
      filterExpressCompany(v){
          v = v.trim();
          if(!v){
            this.expressCompanies = this.expressCompaniesCopy;  
            return;
          }
          this.expressCompanies = this.expressCompaniesCopy.filter(el=>{
            if(el.companyName.includes(v) || el.companyCode.includes(v)){
              return true;
            }
            return false;
          });
      },
      loadExpressCompanies(){
        this.$service.express.listCompany().then(data=>{
          this.expressCompanies = data || [];
          this.expressCompaniesCopy = Object.assign(this.expressCompanies);
        });
      },
      handleSendOrder(row){
        this.currentRow = row;
        this.sendOrderDialogShowed = true;
      },
      submitFormAction(){
        this.$refs.form1.validate(valid => {
            if (valid) {
              this.isSubmiting = true;
              apiObj.sendGoods({
                orderNo:this.currentRow.orderNo,
                expressCompany:this.expressCompanies.find(el=>el.companyCode == this.sendOrderFormData.expressCompanyCode).companyName,
                expressCompanyCode: this.sendOrderFormData.expressCompanyCode,
                expressNo:this.sendOrderFormData.expressNo.trim()
              }).then(()=>{
                this.sendOrderDialogShowed = false;
                this.success();
                this.handleList();
              }).finally(()=>{
                this.isSubmiting = false;
              }); 
            }
        });
      },
      handleCurrentChange(page) {
        this.page.currentPage = page;
        this.handleList();
      },
      handleSizeChange(size) {
        this.page.pageSize = size;
        this.handleList();
      },
    
      handleSelectionChange(args) {
        this.currentSelectedRowIds = args.map(el => el.id);
      },
      hasChanged(params1,params2){
        return Object.keys(params1).some(key=>params2[key] != params1[key]);
    },
    handleSearchChange(params) {
      if(this.hasChanged(params,this.tableQueryParam)){
        this.page.currentPage = 1;
      }
        this.tableQueryParam = params;
        this.handleList();
      },
            
      
      handleRefreshChange() {
        this.handleList();
      },
      /**
       * @title 获取数据
       * @detail 赋值为tableData表格即可
       *
       **/
      handleList() {
        this.tableLoading = true;
        apiObj.listRefund({
          pageNo: this.page.currentPage,
          pageSize: this.page.pageSize,
          ...this.tableQueryParam,
          orderType:this.orderType
        })
          .then(data => {
            this.tableData = data.data || data.dataList || [];
            this.page.total = data.total;
            this.tableLoading = false;
          })
          .catch(() => {
            this.tableLoading = false;
          });
      },     
          
      handleExport() {
        this.downloadLoading = true;
        apiObj.listRefund({
          pageNo: 1,
          pageSize: 3000,
          orderType:this.orderType,
          ...filterForm(this.$refs.crud.searchForm)
        }).then(res => {
          import("@/vendor/Export2Excel").then(excel => {
            const columns = refundOrderInfoTableOption.column.filter(el=>el.hide !== true && el.type!='upload');
            const tHeader = columns.map(el=>el.label);
            const filterVal = columns.map(el=>el.prop);
            const data = this.formatJson(filterVal, res.data || res.dataList);
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: (this.orderType==1?'平台':'主播')  + "退款退货订单" + nowDate()
            });
            this.downloadLoading = false;
          });
        });
      },
      formatJson(filterVal, jsonData) {      
        return jsonData.map(v =>
          filterVal.map(j => {
            return getLabelFromDicV2(this.$refs.crud.DIC,j,v[j]);
          })
        );
      }
    }
  };
  </script>
<style lang="scss" scoped>
.order{
  display: flex;
  padding: 10px 0 10px 60px;
  align-items: center;
  .order__title{
    font-size: 14px;
    font-weight: bold;
  }
  .order__price{
    color:red;
  }
  .order__rules{
    color:blue;
    font-size: 12px;
  }
  .order__img{
    width: 70px;
    height: 70px;
    display: block;
    margin-right: 10px;
  }
}
.order__info{
  padding-left: 20px;
  .order__status{
    font-size: 12px;
  }
}
</style>
